package cn.kuick.match10.test3;

import java.util.Scanner;
import java.util.concurrent.atomic.AtomicInteger;

public class HTMLRender {

	public static String ENDL = "\n";
	public static String SPACE = " ";
	public static int MAX_LINE_COUTN = 80;
	public static String BR = "<br>";
	public static String HR = "<hr>";
	
	public String renderText(String html) {
		Scanner scanner = new Scanner(html);
		StringBuilder sb = new StringBuilder();
		
		AtomicInteger count = new AtomicInteger();
		
		try {
			while(scanner.hasNext()) {
				String token = scanner.next();
				
				if (BR.equals(token)) {
					handleBR(sb, token, count);
				} else if (HR.equals(token)){
					handleHR(sb, token, count);
				} else {
					handleToken(sb, token, count);
				}
			}
			
			sb.append(ENDL);
		} finally {
			scanner.close();
		}
		
		return sb.toString();
	}

	private void handleHR(StringBuilder sb, String token, AtomicInteger count) {
		if (count.intValue() > 0) {
			sb.append(ENDL);
			count.set(0);
		}
		
		for(int i=0; i<MAX_LINE_COUTN; i++) {
			sb.append("-");
		}
		
		sb.append(ENDL);
		count.set(0);
	}

	private void handleBR(StringBuilder sb, String token, AtomicInteger count) {	
		sb.append(ENDL);
		count.set(0);
	}

	private void handleToken(StringBuilder sb, String token, AtomicInteger count) {
		if (count.intValue() + token.length() > MAX_LINE_COUTN) {
			sb.append(ENDL);
			count.set(0);
		} 
		
		if (count.intValue() > 0) {
			sb.append(SPACE);
			count.addAndGet(1);
		}
		
		sb.append(token);
		count.addAndGet(token.length());
	}
}
